from django.shortcuts import render, redirect, HttpResponse

from django import forms

# 通过Ajax在django发送POST请求时免除 csrf_token认证，@csrf_exempt
from django.views.decorators.csrf import csrf_exempt

import json

from app02 import models
from app02.utils.bootstrap import BootStrapModelForm


class taskModelFrom(BootStrapModelForm):
    class Meta:
        model = models.task
        fields = "__all__"
        widgets = {
            # "detail": forms.Textarea
            "detail": forms.TextInput
        }


def task_list(request):
    """ 任务列表  """
    form = taskModelFrom()
    return render(request, 'task_list.html', {"form": form})


@csrf_exempt
def task_ajax(request):
    print(request.GET)
    print(request.POST)
    data_dict = {"status": True, "data": [11, 22, 33, 44, 55]}
    return HttpResponse(json.dumps(data_dict))


@csrf_exempt
def task_add(request):
    print(request.POST)
    # 1.用户发送过来的数据进行验证（ModelForm进行校验）
    form = taskModelFrom(data=request.POST)
    if form.is_valid():  # 如果有效
        form.save()  # 保存到数据库
        data_dict = {"status": True}
        return HttpResponse(json.dumps(data_dict))
    # 不通过，返回错误信息
    data_dict = {"status": False, "error": form.errors}
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))
